import React, { memo, useCallback, useMemo } from 'react';
import { Card, DatePicker, Button, Space, Empty, Timeline, Badge } from 'antd';
import { CalendarOutlined, PlusOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { IDailyScheduleViewProps } from '@/types/components/schedule';
import ScheduleInstanceCard from '../ScheduleInstanceCard';
import styles from './DailyScheduleView.module.css';

/**
 * 每日课表视图组件
 * @description 显示指定日期的课程安排，支持单学生和多学生视图
 */
const DailyScheduleView: React.FC<IDailyScheduleViewProps> = memo(({
  date,
  scheduleInstances,
  students,
  courses,
  viewMode,
  selectedStudents,
  onInstanceClick,
  onDateChange,
  onAddSchedule,
  className,
  readonly = false
}) => {
  // 当前日期的课程实例
  const todayInstances = useMemo(() => {
    return scheduleInstances
      .filter(instance => instance.date === date)
      .filter(instance => 
        viewMode === 'single' 
          ? selectedStudents.includes(instance.studentId)
          : selectedStudents.length === 0 || selectedStudents.includes(instance.studentId)
      )
      .sort((a, b) => a.startTime.localeCompare(b.startTime));
  }, [scheduleInstances, date, viewMode, selectedStudents]);

  // 获取学生信息
  const getStudent = useCallback((studentId: string) => {
    return students.find(s => s.id === studentId);
  }, [students]);

  // 获取课程信息
  const getCourse = useCallback((courseId: string) => {
    return courses.find(c => c.id === courseId);
  }, [courses]);

  // 处理日期变化
  const handleDateChange = useCallback((newDate: dayjs.Dayjs | null) => {
    if (newDate && onDateChange) {
      onDateChange(newDate.format('YYYY-MM-DD'));
    }
  }, [onDateChange]);

  // 处理前一天
  const handlePrevDay = useCallback(() => {
    const prevDay = dayjs(date).subtract(1, 'day').format('YYYY-MM-DD');
    onDateChange?.(prevDay);
  }, [date, onDateChange]);

  // 处理后一天
  const handleNextDay = useCallback(() => {
    const nextDay = dayjs(date).add(1, 'day').format('YYYY-MM-DD');
    onDateChange?.(nextDay);
  }, [date, onDateChange]);

  // 处理添加课程
  const handleAddSchedule = useCallback(() => {
    onAddSchedule?.(date);
  }, [date, onAddSchedule]);

  // 按时间段分组课程实例
  const groupedInstances = useMemo(() => {
    const groups: { [timeSlot: string]: typeof todayInstances } = {};
    
    todayInstances.forEach(instance => {
      const timeSlot = `${instance.startTime}-${instance.endTime}`;
      if (!groups[timeSlot]) {
        groups[timeSlot] = [];
      }
      groups[timeSlot].push(instance);
    });
    
    return Object.entries(groups).sort(([a], [b]) => a.localeCompare(b));
  }, [todayInstances]);

  // 渲染时间轴项目
  const renderTimelineItem = (timeSlot: string, instances: typeof todayInstances) => {
    const [startTime, endTime] = timeSlot.split('-');
    
    return {
      dot: <Badge count={instances.length} size="small" />,
      children: (
        <div className={styles.timeSlotContent}>
          <div className={styles.timeSlotHeader}>
            <span className={styles.timeSlotLabel}>{timeSlot}</span>
            <span className={styles.timeSlotDuration}>
              {dayjs(`2000-01-01 ${endTime}`).diff(dayjs(`2000-01-01 ${startTime}`), 'minute')}分钟
            </span>
          </div>
          <div className={styles.instanceCards}>
            {instances.map(instance => {
              const student = getStudent(instance.studentId);
              const course = getCourse(instance.courseId);
              
              if (!student || !course) return null;
              
              return (
                <ScheduleInstanceCard
                  key={instance.id}
                  instance={instance}
                  student={student}
                  course={course}
                  onEdit={() => onInstanceClick?.(instance)}
                  size="small"
                  readonly={readonly}
                  className={styles.instanceCard}
                />
              );
            })}
          </div>
        </div>
      )
    };
  };

  // 渲染空状态
  const renderEmpty = () => (
    <div className={styles.emptyContainer}>
      <Empty
        description={`${dayjs(date).format('YYYY年MM月DD日')} 暂无课程安排`}
        image={Empty.PRESENTED_IMAGE_SIMPLE}
      >
        {!readonly && (
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAddSchedule}>
            添加课程
          </Button>
        )}
      </Empty>
    </div>
  );

  return (
    <div className={`${styles.dailyScheduleView} ${className || ''}`}>
      {/* 头部控制区域 */}
      <Card className={styles.headerCard} size="small">
        <div className={styles.headerContent}>
          <div className={styles.dateControls}>
            <Button
              type="text"
              icon={<LeftOutlined />}
              onClick={handlePrevDay}
              className={styles.navButton}
            />
            <DatePicker
              value={dayjs(date)}
              onChange={handleDateChange}
              format="YYYY-MM-DD"
              allowClear={false}
              className={styles.datePicker}
            />
            <Button
              type="text"
              icon={<RightOutlined />}
              onClick={handleNextDay}
              className={styles.navButton}
            />
          </div>
          
          <div className={styles.headerInfo}>
            <span className={styles.weekDay}>
              {dayjs(date).format('dddd')}
            </span>
            <Badge 
              count={todayInstances.length} 
              showZero 
              className={styles.countBadge}
            />
          </div>
          
          {!readonly && (
            <Space>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={handleAddSchedule}
              >
                添加课程
              </Button>
            </Space>
          )}
        </div>
      </Card>

      {/* 课程列表区域 */}
      <Card className={styles.contentCard}>
        {todayInstances.length === 0 ? (
          renderEmpty()
        ) : (
          <div className={styles.timelineContainer}>
            <Timeline
              items={groupedInstances.map(([timeSlot, instances]) => 
                renderTimelineItem(timeSlot, instances)
              )}
              className={styles.scheduleTimeline}
            />
          </div>
        )}
      </Card>
    </div>
  );
});

DailyScheduleView.displayName = 'DailyScheduleView';

export default DailyScheduleView;